package client.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.ViewPropertyAnimatorListenerAdapter;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import java.util.ArrayList;

import client.PhotoClient;
import client.PhotoMoreResultBean;
import client.PhotoPreviewClient;
import client.R;
import client.activity.BGAPhotoPickerPreviewActivity;
import client.adapter.BGAPhotoPageAdapter;
import client.photoview.PhotoViewAttacher;
import client.widget.BGAHackyViewPager;

/**
 * 项目名称：client.fragment
 * 创建人:LuoFG
 * 创建时间:2021/9/15  13:41
 * 描述:
 * 作用:
 */
public class PhotoPickerPreviewFragment extends Fragment implements PhotoViewAttacher.OnViewTapListener {

    private TextView mTitleTv, mTitleNum,mTvNum;
    private BGAHackyViewPager mContentHvp;
    private RelativeLayout reyMore,reyBack,reyTitle;

    private BGAPhotoPageAdapter mPhotoPageAdapter;
    private Activity activity;

    private boolean mIsHidden = false;
    /**
     * 上一次标题栏显示或隐藏的时间戳
     */
    private long mLastShowHiddenTime;

    public BGAPhotoPickerPreviewActivity.MoreBackClickListener moreBackClickListener;

    public BGAPhotoPickerPreviewActivity.MoreBackClickListener getMoreBackClickListener(){
        if(moreBackClickListener==null) {
            moreBackClickListener = photoRefreshBean -> {
                if(mPhotoPageAdapter!=null&&mContentHvp!=null){
                    mPhotoPageAdapter.setPreviewPhotos(photoRefreshBean.getPaths());
                    mPhotoPageAdapter.notifyDataSetChanged();
                    mContentHvp.setAdapter(mPhotoPageAdapter);
                    mContentHvp.setCurrentItem(photoRefreshBean.getPosition());
                }
            };
        }
        return moreBackClickListener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity=getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_photo_picker_preview, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }



    @Override
    public void onResume() {
        super.onResume();
    }

    private void initView(View view){
        mContentHvp = view.findViewById(R.id.viewpager);
        reyBack = view.findViewById(R.id.rey_back);
        reyMore = view.findViewById(R.id.rey_more);
        reyTitle = view.findViewById(R.id.rey_title);
        mTitleTv = view.findViewById(R.id.tv_title);
        mTitleNum = view.findViewById(R.id.tv_right_num);
        mTvNum = view.findViewById(R.id.tv_photo_num);

        initTitle();
        setListener();
        processLogic();
    }


    protected void setListener() {
        mContentHvp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                handlePageSelectedStatus();
            }
        });
    }

    protected void processLogic() {
        //图片选择数据
        ArrayList<String> previewPhotos= PhotoPreviewClient.getClient().getSelectPhotoList();
        int currentPosition = PhotoPreviewClient.getClient().getmCurrentPosition();

        mPhotoPageAdapter = new BGAPhotoPageAdapter(this, previewPhotos);
        mContentHvp.setAdapter(mPhotoPageAdapter);
        mContentHvp.setCurrentItem(currentPosition);

        //如果客户端注册了保存图片的方法  则需要监听这个方法  去执行保存图片
        if(PhotoPreviewClient.getClient().getGetSaveShowImageListener()!=null){
            PhotoPreviewClient.getClient().addSaveShowImageListener(new PhotoPreviewClient.SaveShowImageListener() {
                @Override
                public void save() {
                    String path=mPhotoPageAdapter.savePositionImage(mContentHvp.getCurrentItem());
                    Log.e("远程保存的图片",path);
                    //返回给客户端的保存图片
                    PhotoPreviewClient.getClient().runGetSaveShowImage(path);
                }
            });
        }

        // 过2秒隐藏标题栏和底部选择栏
        reyTitle.postDelayed(new Runnable() {
            @Override
            public void run() {
                hiddenToolBarAndChooseBar();
            }
        }, 6000);
    }

    public void initTitle() {
        if(!PhotoPreviewClient.getClient().isShowTitle()){
            return;
        }
        //设置背景
        reyTitle.setVisibility(View.VISIBLE);
        reyTitle.setBackgroundColor(ContextCompat.getColor(activity, PhotoPreviewClient.getClient().getBarBgColor()));
        //设置标题
        mTitleTv.setText(PhotoPreviewClient.getClient().getStrTitle());
        mTitleTv.setTextColor(ContextCompat.getColor(activity, PhotoPreviewClient.getClient().getBarTextColor()));
        //设置更多或者标题栏右数字
        if(PhotoPreviewClient.getClient().isShowMore()){
            reyMore.setVisibility(View.VISIBLE);
            mTitleNum.setVisibility(View.GONE);
            reyMore.setOnClickListener(v -> {
                PhotoPreviewClient.getClient().runMoreClickLister(new PhotoMoreResultBean(PhotoPreviewClient.getClient().getPhotoResultTag(), mPhotoPageAdapter.getmPreviewPhotos(),mContentHvp.getCurrentItem(),activity,getMoreBackClickListener()));
            });
        }else{
            reyMore.setVisibility(View.GONE);
            mTitleNum.setVisibility(View.VISIBLE);
            mTitleNum.setTextColor(ContextCompat.getColor(activity, PhotoPreviewClient.getClient().getBarTextColor()));
        }

        if(PhotoClient.getClient().isShowBtmNum()) {
            mTvNum.setVisibility(View.VISIBLE);
            mTvNum.setTextColor(ContextCompat.getColor(getActivity(), PhotoClient.getClient().getBarBgColor()));
        }else{
            mTvNum.setVisibility(View.GONE);
        }

        reyBack.setVisibility(View.VISIBLE);
        //设置返回键
        reyBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.finish();
            }
        });

        handlePageSelectedStatus();
    }


    private void handlePageSelectedStatus() {
        if (mTitleTv == null || mPhotoPageAdapter == null) {
            return;
        }

        if (PhotoPreviewClient.getClient().isShowMore()) {
            mTvNum.setText((mContentHvp.getCurrentItem() + 1) + "/" + mPhotoPageAdapter.getCount());
        } else {
            mTitleNum.setText((mContentHvp.getCurrentItem() + 1) + "/" + mPhotoPageAdapter.getCount());
        }
    }


    @Override
    public void onViewTap(View view, float x, float y) {
        if (System.currentTimeMillis() - mLastShowHiddenTime > 500) {
            mLastShowHiddenTime = System.currentTimeMillis();
            if (mIsHidden) {
                showTitleBarAndChooseBar();
            } else {
                hiddenToolBarAndChooseBar();
            }
        }
    }

    /**
     * 显示标题栏
     */
    private void showTitleBarAndChooseBar() {
        if (reyTitle != null) {
            ViewCompat.animate(reyTitle).translationY(0).setInterpolator(new DecelerateInterpolator(2)).setListener(new ViewPropertyAnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(View view) {
                    mIsHidden = false;
                }
            }).start();

        }
    }

    /**
     * 隐藏标题栏
     */
    private void hiddenToolBarAndChooseBar() {
        if (reyTitle != null) {
            ViewCompat.animate(reyTitle).translationY(-reyTitle.getHeight()).setInterpolator(new DecelerateInterpolator(2)).setListener(new ViewPropertyAnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(View view) {
                    mIsHidden = true;
                }
            }).start();

        }
    }

}
